/*============================================================================
 * Copyright 2009 VMware Inc.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at: http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 ============================================================================*/

package com.vmware.vcloud.tmrk;

import java.io.IOException;
import java.net.MalformedURLException;

import org.dom4j.Document;
import org.dom4j.Element;

import com.vmware.vcloud.VCloudObject;
import com.vmware.vcloud.data.XmlBuilder;
import com.vmware.vcloud.data.XmlUtil;
import com.vmware.vcloud.rest.RestClient;

/**
 * @author Steve Jin (sjin@vmware.com)
 */

public class InternetService extends VCloudObject 
{
	PublicIpAddress pia;
	String protocol;
	int port;
	boolean enabled;
	int timeout;
	String description;
	
	public InternetService(RestClient rc, String href) throws MalformedURLException
	{
		super(rc, href);
	}
	
	public InternetService(RestClient rc, String href, String name) throws MalformedURLException
	{
		super(rc, href, name);
	}
	
	protected void parse() throws MalformedURLException
	{
		Element piaElem = root.element("PublicIpAddress");
		pia = XmlUtil.createPublicIpAddress(rc, piaElem);
	}
	
	public Node addNode(String privateIp, String name, int port, String description) throws IOException
	{
		String reqBody = XmlBuilder.buildAddNodeReq(privateIp, name, port, description);
		
		String resBody = rc.post(getURL() + "/nodes", reqBody, "application/xml");
		System.out.println("addNode req:" + getURL() + "/nodes");
		System.out.println("addNode reqBody:" + reqBody);
		System.out.println("addNode resBody:" + resBody);
		Document doc = XmlUtil.getDocument(resBody);

	    String href = doc.getRootElement().elementText("Href");
	    System.out.println("href:" + href);
	    
	    return new Node(rc, href);
	}

	public void delete() throws IOException
	{
		rc.delete(getURL());
	}
	
	public PublicIpAddress getPublicIpAddress() throws IOException
	{
		this.loadContentIfNotYet();
		return pia;
	}
	
	public Node[] getNodes()
	{
		return new Node[0];
		//TODO
	}
	
}
